package br.financeiro;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.Toast;
import br.financeiro.adapters.ItemListView;
import br.financeiro.adapters.SimpleExpandableAdapter;
import br.financeiro.dao.DBHelper;
import br.financeiro.entities.Mail;
import br.financeiro.entities.Person;
import br.financeiro.entities.Phone;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;

public class SearchPerson extends OrmLiteBaseActivity<DBHelper> {
	private Dao<Person, Integer> dao = null;
	private OnClickListener btnNewListener = new OnClickListener() {

		@Override
		public void onClick( View view ) {
			Intent intent = new Intent( SearchPerson.this, CreatePerson.class );
			overridePendingTransition( android.R.anim.fade_in, android.R.anim.slide_out_right );
			startActivity( intent );
		}
	};

	protected void onResume() {
		super.onResume();
		loadPersons();
	};

	private void loadPersons() {
		final ExpandableListView listView = (ExpandableListView) findViewById( R.id.expandable_list );
		List<Person> persons = null;

		try {
			dao = getHelper().getPersonDao();
			persons = dao.queryForAll();
		} catch ( SQLException e ) {
			Toast.makeText( this, "Ocorreu um erro no banco de dados", Toast.LENGTH_LONG ).show();
			this.finish();
			return;
		}
		// cria uma lista de itens
		ArrayList<ItemListView> itens = new ArrayList<ItemListView>();
		for ( Person person : persons ) {

			ItemListView iten = new ItemListView( person.getName(), person.getId() );
			for ( Phone phone : person.getPhones() ) {
				iten.addItem( phone.getNumber(), phone.getType().getIcon() );
			}
			for ( Mail mail : person.getMails() ) {
				iten.addItem( mail.getMail() + mail.getType().getDomain(), mail.getType().getIcon() );
			}

			itens.add( iten );
		}
		listView.setAdapter( new SimpleExpandableAdapter( SearchPerson.this, itens ) );
		listView.setLongClickable( true );

		Button btnNew = (Button) findViewById( R.id.btnNew );

		btnNew.setOnClickListener( btnNewListener );
	}

	@Override
	protected void onCreate( Bundle savedInstanceState ) {
		super.onCreate( savedInstanceState );
		setContentView( R.layout.activity_search_person );
		loadPersons();
	}
}